import struct
import random

# QKD Packet Fields
HEADER_FORMAT = "!I H B B I I I"

class QKDAppPacket:
    header_length = 0
    def __init__(self, length=0, msg_id=0, encryption_algo=0, auth_algo=0, encryption_key_id=0, auth_key_id=0, auth_tag=0, payload=b''):
        self.length = length  # Length: 数据包的总大小，包括长度字段本身
        self.msg_id = msg_id  # Msg-Id: 消息编号
        self.encryption_algo = encryption_algo  # E: 使用的加密密码类型，其中值 0 表示未加密的数据包
        self.auth_algo = auth_algo  # A: 使用的认证算法的类型，其中值 0 表示未经认证的数据包
        self.encryption_key_id = encryption_key_id  # E-KeyId: 加密密钥 ID
        self.auth_key_id = auth_key_id  # A-KeyId: 身份验证密钥 ID
        self.auth_tag = auth_tag  # A-Tag: 身份验证标签
        self.payload = payload  # QKD Application 014
        self.header_length = struct.calcsize(HEADER_FORMAT)

    def pack(self):
        # Pack the header and payload into bytes
        header = struct.pack(HEADER_FORMAT, self.length, self.msg_id, self.encryption_algo, self.auth_algo,
                            self.encryption_key_id, self.auth_key_id, self.auth_tag)
        return header + self.payload

    @staticmethod
    def unpack(data):
        # Unpack the received data into the QKDAppPacket fields
        header_size = struct.calcsize(HEADER_FORMAT)
        header = data[:header_size]
        payload = data[header_size:]
        unpacked_data = struct.unpack(HEADER_FORMAT, header)
        return QKDAppPacket(*unpacked_data, payload)

    def print_packet(self):
        print("PacketPrint")
        # Print packet fields for debugging
        print(f"Length: {self.length}")
        print(f"Msg-Id: {self.msg_id}")
        print(f"Encryption Algorithm: {self.encryption_algo}")
        print(f"Authentication Algorithm: {self.auth_algo}")
        print(f"Encryption Key ID: {self.encryption_key_id}")
        print(f"Authentication Key ID: {self.auth_key_id}")
        print(f"Authentication Tag: {self.auth_tag}")
        print(f"Payload: {self.payload}")
        print(f"Header Length: {self.header_length}")
